
import { Socket } from 'socket.io-client';
import io from 'socket.io-client/dist/socket.io.js';
import { EventName } from '../../Frame/Script/const/eventName';
import { App } from '../app';
import GameLogic from '../gameLogic';

/**
 * 使用socket.io 进行网络连接的
 */
export default class SocketIO {
	private static socketIo: Socket;
	private static _isLinkIng: boolean = false //是否已经连接

	//开始进行socketIO连接
	public static toConnect() {
		if (this._isLinkIng) return
		let playerToken = GameLogic.getPlayerToken()
		this._isLinkIng = true
		let socketUrl = GameLogic.getSocketIOUrl()
		let socketIoInstance: Socket = io(socketUrl,
			{
				withCredentials: true,
				extraHeaders: {
					"token": playerToken,
				},
				transports: ['polling', 'websocket', 'webtransport'],
			});

		this.socketIo = socketIoInstance
		this._registerSocketListeningEvent(socketIoInstance)
		this._registerListeningEvent(socketIoInstance)
	}

	//关闭socketIO连接
	public static closeSocket() {
		this._isLinkIng = false
		if (this.socketIo) {
			this.socketIo.close()
		}
	}

	/**
	 * 注册的Socket 原生事件监听
	 */
	private static _registerSocketListeningEvent(socketIoInstance: Socket) {
		//连接成功
		socketIoInstance.on("connect", () => {
			console.log("SocketIO连接成功", CC_DEV, CC_DEBUG);
			window["callByNative"] = function () {
				console.log("java 调用安卓")
			}
			App.event.emit(EventName.Game.SocketConnectSucceed)
		});

		//关闭连接
		function closeHandler(reason: string) {
			this._isLinkIng = false
			this._beginCostTime = Date.now()
			if (reason == "io client disconnect") {
				//客户端主动断开
			} else if (reason == "io server disconnect") {
				//服务器主动断开
			} else {

			}
		}

		/**
		 * 断开连接 服务器强制断开 客户端手动断开 或者其他情况 前两种需要重新发起
		 * io client disconnect 这种是客户端手动断开的
		 * io server disconnect 这种是服务器踢出去的
		 */
		socketIoInstance.on("disconnect", (reason: any) => {
			closeHandler.call(this, reason)
		})

		//在连接错误时触发
		socketIoInstance.on("error", (err: any) => {
			closeHandler.call(this)
		})

		// 发生命名空间中间件错误时触发
		socketIoInstance.on("connect_error", (err: any) => {
			closeHandler.call(this)
		});
	}

	/**
	* 注册的自定义事件监听
	*/
	private static _registerListeningEvent(socketIoInstance: Socket) {


	}

}